package com.aiyige.page.authentication;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.view.TextureView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.request.SubmitPersonalCertificationRequest;
import com.aiyige.page.authentication.model.Authentication;
import com.aiyige.page.publish.photo.model.PublishPhotoItem;
import com.aiyige.utils.DialogUtil;
import com.aiyige.utils.EditTextAutoMoveCursorToEndFocusChangeListener;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.TextWatcherAdapter;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UploadPhotoUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.RoundCornerImageView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;


@Route(path = ARouterConfig.PersonalAuthenticationPage)
public class PersonalAuthenticationPage extends AppCompatActivity {
    public static final int REQUEST_CODE_HOLDING_ID_CARD = 1;
    public static final int REQUEST_CODE_ID_CARD_FRONT = 2;
    public static final int REQUEST_CODE_ID_CARD_BACK = 3;
    public static final int NEXT = 4;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    TextView titleActionBtn;
    @BindView(R.id.realNameLabel)
    TextView realNameLabel;
    @BindView(R.id.realNameEt)
    EditText realNameEt;
    @BindView(R.id.idNumLabel)
    TextView idNumLabel;
    @BindView(R.id.idNumEt)
    EditText idNumEt;
    @BindView(R.id.holdingIdCardBgIv)
    ImageView holdingIdCardBgIv;
    @BindView(R.id.holdingIdCardTv)
    TextView holdingIdCardTv;
    @BindView(R.id.holdingIdCardIv)
    RoundCornerImageView holdingIdCardIv;
    @BindView(R.id.holdingIdCardDeleteIv)
    ImageView holdingIdCardDeleteIv;
    @BindView(R.id.holdingIDCardLayout)
    ConstraintLayout holdingIDCardLayout;
    @BindView(R.id.idCardFrontBgIv)
    ImageView idCardFrontBgIv;
    @BindView(R.id.idCardFrontIv)
    RoundCornerImageView idCardFrontIv;
    @BindView(R.id.idCardFrontDeleteIv)
    ImageView idCardFrontDeleteIv;
    @BindView(R.id.idCardFrontTv)
    TextView idCardFrontTv;
    @BindView(R.id.idCardFrontLayout)
    ConstraintLayout idCardFrontLayout;
    @BindView(R.id.idCardBackBgIv)
    ImageView idCardBackBgIv;
    @BindView(R.id.idCardBackIv)
    RoundCornerImageView idCardBackIv;
    @BindView(R.id.idCardBackDeleteIv)
    ImageView idCardBackDeleteIv;
    @BindView(R.id.idCardBackTv)
    TextView idCardBackTv;
    @BindView(R.id.idCardBackLayout)
    ConstraintLayout idCardBackLayout;
    @Autowired
    Authentication authentication = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_authentication_page);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (authentication == null) {
            ToastX.show(R.string.unknown_error);
            finish();
            return;
        }
        realNameEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                authentication.setPersonalName(s.toString());
            }
        });
        realNameEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
        idNumEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                authentication.setPersonalIdNum(s.toString());
            }
        });
        idNumEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
        titleTv.setText(R.string.personal_user_authentication);
        updateView();
    }

    public void updateView() {
        if (authentication.isReadOnly()) {
            titleActionBtn.setText(R.string.reauthentication);
        } else {
            titleActionBtn.setText(R.string.submit_authentication);
        }
        realNameEt.setText(authentication.getPersonalName());
        idNumEt.setText(authentication.getPersonalIdNum());
        if (TextUtils.isEmpty(authentication.getPersonalHoldingIdCardLocalUrl())
                && TextUtils.isEmpty(authentication.getPersonalHoldingIdCardRemoteUrl())) {
            holdingIdCardIv.setVisibility(View.INVISIBLE);
            holdingIdCardDeleteIv.setVisibility(View.INVISIBLE);
            holdingIdCardBgIv.setVisibility(View.VISIBLE);
            holdingIdCardTv.setVisibility(View.VISIBLE);
        } else {
            holdingIdCardBgIv.setVisibility(View.INVISIBLE);
            holdingIdCardTv.setVisibility(View.INVISIBLE);
            holdingIdCardIv.setVisibility(View.VISIBLE);
            holdingIdCardDeleteIv.setVisibility(authentication.isReadOnly() ? View.INVISIBLE : View.VISIBLE);
            String photoUrl = !TextUtils.isEmpty(authentication.getPersonalHoldingIdCardRemoteUrl()) ? authentication.getPersonalHoldingIdCardRemoteUrl() : authentication.getPersonalHoldingIdCardLocalUrl();
            Glide.with(this).asBitmap().load(photoUrl)
                    .apply(RequestOptions.placeholderOf(R.color.transparent))
                    .into(holdingIdCardIv);
        }


        if (TextUtils.isEmpty(authentication.getPersonalIdCardFrontLocalUrl())
                && TextUtils.isEmpty(authentication.getPersonalIdCardFrontRemoteUrl())) {
            idCardFrontIv.setVisibility(View.INVISIBLE);
            idCardFrontDeleteIv.setVisibility(View.INVISIBLE);
            idCardFrontBgIv.setVisibility(View.VISIBLE);
            idCardFrontTv.setVisibility(View.VISIBLE);
        } else {
            idCardFrontBgIv.setVisibility(View.INVISIBLE);
            idCardFrontTv.setVisibility(View.INVISIBLE);
            idCardFrontIv.setVisibility(View.VISIBLE);
            idCardFrontDeleteIv.setVisibility(authentication.isReadOnly() ? View.INVISIBLE : View.VISIBLE);
            String photoUrl = !TextUtils.isEmpty(authentication.getPersonalIdCardFrontRemoteUrl()) ? authentication.getPersonalIdCardFrontRemoteUrl() : authentication.getPersonalIdCardFrontLocalUrl();
            Glide.with(this).asBitmap().load(photoUrl)
                    .apply(RequestOptions.placeholderOf(R.color.transparent))
                    .into(idCardFrontIv);
        }

        if (TextUtils.isEmpty(authentication.getPersonalIdCardBackLocalUrl())
                && TextUtils.isEmpty(authentication.getPersonalIdCardBackRemoteUrl())) {
            idCardBackIv.setVisibility(View.INVISIBLE);
            idCardBackDeleteIv.setVisibility(View.INVISIBLE);
            idCardBackBgIv.setVisibility(View.VISIBLE);
            idCardBackTv.setVisibility(View.VISIBLE);
        } else {
            idCardBackBgIv.setVisibility(View.INVISIBLE);
            idCardBackTv.setVisibility(View.INVISIBLE);
            idCardBackIv.setVisibility(View.VISIBLE);
            idCardBackDeleteIv.setVisibility(authentication.isReadOnly() ? View.INVISIBLE : View.VISIBLE);
            String photoUrl = !TextUtils.isEmpty(authentication.getPersonalIdCardBackRemoteUrl()) ? authentication.getPersonalIdCardBackRemoteUrl() : authentication.getPersonalIdCardBackLocalUrl();
            Glide.with(this).asBitmap().load(photoUrl)
                    .apply(RequestOptions.placeholderOf(R.color.transparent))
                    .into(idCardBackIv);
        }
    }

    @Override
    public void onBackPressed() {
        DialogUtil.makeConfirmExitDialog(this, R.string.confirm_exit_edit, R.string.abandon, R.string.cancel).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case NEXT:
                setResult(RESULT_OK);
                finish();
                break;
            case REQUEST_CODE_HOLDING_ID_CARD:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = ListUtil.getFirstItem(selectList);
                    if (localMedia != null) {
                        authentication.setPersonalHoldingIdCardLocalUrl(localMedia.getPath());
                        authentication.setPersonalHoldingIdCardRemoteUrl("");
                        updateView();
                        UploadPhotoUtil.newBuilder()
                                .photoLocalUrl(authentication.getPersonalHoldingIdCardLocalUrl())
                                .listener(new UploadPhotoUtil.Listener() {
                                    LoadingDialog loadingDialog;

                                    @Override
                                    public void onPreUpload() {
                                        loadingDialog = LoadingDialog.newBuilder()
                                                .with(PersonalAuthenticationPage.this)
                                                .message(R.string.uploading)
                                                .cancelable(false)
                                                .show();
                                    }

                                    @Override
                                    public void onProgress(double progress) {

                                    }

                                    @Override
                                    public void onFail(Throwable t) {
                                        loadingDialog.dismiss();
                                        ToastX.show(R.string.upload_failed);
                                        authentication.setPersonalHoldingIdCardRemoteUrl("");
                                        authentication.setPersonalHoldingIdCardLocalUrl("");
                                        updateView();
                                    }

                                    @Override
                                    public void onFinish(String url) {
                                        loadingDialog.dismiss();
                                        authentication.setPersonalHoldingIdCardRemoteUrl(url);
                                    }
                                })
                                .build()
                                .upload();
                    }
                }
                break;
            case REQUEST_CODE_ID_CARD_FRONT:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = ListUtil.getFirstItem(selectList);
                    if (localMedia != null) {
                        authentication.setPersonalIdCardFrontLocalUrl(localMedia.getPath());
                        authentication.setPersonalIdCardFrontRemoteUrl("");
                        updateView();
                        UploadPhotoUtil.newBuilder()
                                .photoLocalUrl(authentication.getPersonalIdCardFrontLocalUrl())
                                .listener(new UploadPhotoUtil.Listener() {
                                    LoadingDialog loadingDialog;

                                    @Override
                                    public void onPreUpload() {
                                        loadingDialog = LoadingDialog.newBuilder()
                                                .with(PersonalAuthenticationPage.this)
                                                .message(R.string.uploading)
                                                .cancelable(false)
                                                .show();
                                    }

                                    @Override
                                    public void onProgress(double progress) {

                                    }

                                    @Override
                                    public void onFail(Throwable t) {
                                        loadingDialog.dismiss();
                                        ToastX.show(R.string.upload_failed);
                                        authentication.setPersonalIdCardFrontRemoteUrl("");
                                        authentication.setPersonalIdCardFrontLocalUrl("");
                                        updateView();
                                    }

                                    @Override
                                    public void onFinish(String url) {
                                        loadingDialog.dismiss();
                                        authentication.setPersonalIdCardFrontRemoteUrl(url);
                                    }
                                })
                                .build()
                                .upload();
                    }
                }
                break;
            case REQUEST_CODE_ID_CARD_BACK:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = ListUtil.getFirstItem(selectList);
                    if (localMedia != null) {
                        authentication.setPersonalIdCardBackLocalUrl(localMedia.getPath());
                        authentication.setPersonalIdCardBackRemoteUrl("");
                        updateView();
                        UploadPhotoUtil.newBuilder()
                                .photoLocalUrl(authentication.getPersonalIdCardBackLocalUrl())
                                .listener(new UploadPhotoUtil.Listener() {
                                    LoadingDialog loadingDialog;

                                    @Override
                                    public void onPreUpload() {
                                        loadingDialog = LoadingDialog.newBuilder()
                                                .with(PersonalAuthenticationPage.this)
                                                .message(R.string.uploading)
                                                .cancelable(false)
                                                .show();
                                    }

                                    @Override
                                    public void onProgress(double progress) {

                                    }

                                    @Override
                                    public void onFail(Throwable t) {
                                        loadingDialog.dismiss();
                                        ToastX.show(R.string.upload_failed);
                                        authentication.setPersonalIdCardBackRemoteUrl("");
                                        authentication.setPersonalIdCardBackLocalUrl("");
                                        updateView();
                                    }

                                    @Override
                                    public void onFinish(String url) {
                                        loadingDialog.dismiss();
                                        authentication.setPersonalIdCardBackRemoteUrl(url);
                                    }
                                })
                                .build()
                                .upload();
                    }
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    public boolean checkFormValidate() {
        boolean result = true;
        if (TextUtils.isEmpty(authentication.getPersonalName())) {
            result = false;
        }
        if (TextUtils.isEmpty(authentication.getPersonalIdNum())) {
            result = false;
        }
        if (TextUtils.isEmpty(authentication.getPersonalHoldingIdCardRemoteUrl())) {
            result = false;
        }
        if (TextUtils.isEmpty(authentication.getPersonalIdCardFrontRemoteUrl())) {
            result = false;
        }
        if (TextUtils.isEmpty(authentication.getPersonalIdCardBackRemoteUrl())) {
            result = false;
        }
        return result;
    }


    public void doSubmit() {
        new SubmitTask(this).execute();
    }

    public class SubmitTask extends SafeAsyncTask<Object, Object, Object> {

        public SubmitTask(Activity activity) {
            super(activity, R.string.text_process);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                ARouter.getInstance()
                        .build(ARouterConfig.WaitingAuthenticationPage)
                        .navigation(PersonalAuthenticationPage.this, NEXT);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .submitPersonalCertification(SubmitPersonalCertificationRequest.newBuilder()
                                .IDCardBackUrl(authentication.getPersonalIdCardBackRemoteUrl())
                                .IDCardFrontUrl(authentication.getPersonalIdCardFrontRemoteUrl())
                                .IDCardHoldUrl(authentication.getPersonalHoldingIdCardRemoteUrl())
                                .IDCardName(authentication.getPersonalName())
                                .IDCardNo(authentication.getPersonalIdNum())
                                .build()).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }


    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn, R.id.holdingIdCardBgIv, R.id.holdingIdCardDeleteIv, R.id.idCardFrontBgIv, R.id.idCardFrontDeleteIv, R.id.idCardBackBgIv, R.id.idCardBackDeleteIv})
    public void onViewClicked(View view) {
        realNameEt.clearFocus();
        idNumEt.clearFocus();
        switch (view.getId()) {
            case R.id.titleBackBtn:
                DialogUtil.makeConfirmExitDialog(this, R.string.confirm_exit_authentication, R.string.confirm, R.string.cancel).show();
                break;
            case R.id.titleActionBtn:
                if (authentication.isReadOnly()) {
                    authentication = Authentication.newBuilder()
                            .userType(Authentication.USER_TYPE_PERSONAL)
                            .readOnly(false)
                            .build();
                    updateView();
                } else if (checkFormValidate()) {
                    doSubmit();
                }
                break;
            case R.id.holdingIdCardBgIv:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(false)
                        .enableCrop(false)
                        .isCamera(true)
                        .isGif(false)
                        .compress(false)
                        .imageSpanCount(4)
                        .forResult(REQUEST_CODE_HOLDING_ID_CARD);
                break;
            case R.id.holdingIdCardDeleteIv:
                authentication.setPersonalHoldingIdCardLocalUrl("");
                authentication.setPersonalHoldingIdCardRemoteUrl("");
                updateView();
                break;
            case R.id.idCardFrontBgIv:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(false)
                        .enableCrop(false)
                        .isCamera(true)
                        .isGif(false)
                        .compress(false)
                        .imageSpanCount(4)
                        .forResult(REQUEST_CODE_ID_CARD_FRONT);
                break;
            case R.id.idCardFrontDeleteIv:
                authentication.setPersonalIdCardFrontLocalUrl("");
                authentication.setPersonalIdCardFrontRemoteUrl("");
                updateView();
                break;
            case R.id.idCardBackBgIv:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(false)
                        .enableCrop(false)
                        .isCamera(true)
                        .isGif(false)
                        .compress(false)
                        .imageSpanCount(4)
                        .forResult(REQUEST_CODE_ID_CARD_BACK);
                break;
            case R.id.idCardBackDeleteIv:
                authentication.setPersonalIdCardBackLocalUrl("");
                authentication.setPersonalIdCardBackRemoteUrl("");
                updateView();
                break;
        }
    }
}
